package me.spring.cloud.components.starter.elastic.job.lite.configure;

import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperConfiguration;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import me.spring.cloud.common.components.elasticjob.lite.parser.ElasticJobConfParser;
import me.spring.cloud.common.components.elasticjob.lite.properties.ZookeeperProperties;
import me.spring.cloud.common.components.elasticjob.lite.service.ElasticJobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 任务自动配置
 */
@Configuration
@AutoConfigureAfter(ElasticJobDbLogConfiguration.class)
@EnableConfigurationProperties(ZookeeperProperties.class)
public class ElasticJobParserConfiguration {

  @Autowired
  private ZookeeperProperties zookeeperProperties;

  /**
   * 初始化Zookeeper注册中心
   * @return
   */
  @Bean(initMethod = "init")
  public ZookeeperRegistryCenter zookeeperRegistryCenter() {
    ZookeeperConfiguration zkConfig = new ZookeeperConfiguration(zookeeperProperties.getServerLists(),
        zookeeperProperties.getNamespace());
    zkConfig.setBaseSleepTimeMilliseconds(zookeeperProperties.getBaseSleepTimeMilliseconds());
    zkConfig.setConnectionTimeoutMilliseconds(zookeeperProperties.getConnectionTimeoutMilliseconds());
    zkConfig.setDigest(zookeeperProperties.getDigest());
    zkConfig.setMaxRetries(zookeeperProperties.getMaxRetries());
    zkConfig.setMaxSleepTimeMilliseconds(zookeeperProperties.getMaxSleepTimeMilliseconds());
    zkConfig.setSessionTimeoutMilliseconds(zookeeperProperties.getSessionTimeoutMilliseconds());
    return new ZookeeperRegistryCenter(zkConfig);
  }

  @Bean
  public ElasticJobService elasticJobService() {
    return new ElasticJobService();
  }

  @Bean
  public ElasticJobConfParser elasticJobConfParser() {
    return new ElasticJobConfParser();
  }

}
